const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const validateForm = (jsonData, formData, successCallback, errorCallback) => {
  let succeed = true
  let errorMsg = ""
  for (let index = 0; index < jsonData.length; index++) {
    const element = jsonData[index];
    if (element.valid) {
      console.log(444,formData[`${element.keyName}`]);
      /* 普通必填规则 */
      if (!formData[`${element.keyName}`]) {
        succeed = false
        errorMsg = element.label + "不能为空"
        break
      } else {

        /* 特殊校验规则 */
        // 正则
        if (element.regex) {
          let regexs = new RegExp(element.regex)
          if (!regexs.test(formData[`${element.keyName}`])) {
            succeed = false
            errorMsg = "请输入正确的" + element.label
            break
          }
        }
        //表格/检查项
        if(element.tempType=="table"||element.tempType=="inspect"){
          for (let index = 0; index <  element.value.length; index++) {
            const item =  element.value[index];
            if(!item.value){
              succeed = false
              errorMsg = element.tempType=="inspect"?("请检查" + item.label):("请输入" + item.label)
              break
            }
          }
        }
        if(element.tempType=="address"){
          if(!element.cascader){
            succeed = false
            errorMsg = "请选择省市区街道"
            break
          }
        }
        if(element.tempType=="upload"){
          if(element.value==null||element.value.length==0){
            succeed = false
            errorMsg = "请上传" + element.label
            break
          }
        }
      }
    }
  }
  if (succeed) {
    successCallback()
  } else {
    errorCallback(errorMsg)
  }
}

module.exports = {
  formatTime,
  validateForm
}
